<template>
    <div style="padding-left: 50px;margin-top: 40px;height: 596px;">
        <el-row :gutter="15">
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px">
                <el-col :span="11">
                    <el-form-item label="用户名：" prop="userName">
                        <el-input v-model="formData.userName" disabled placeholder="默认用户登录用户名" :maxlength="11"
                            show-word-limit clearable :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="机构类型：" prop="type">
                        <el-select v-model="formData.type" placeholder="请选择机构类" style="width: 328px;">
                            <el-option v-for="dict in dict.type.user_auth_role_type_two" :key="dict.value"
                                :label="dict.label" :value="dict.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="机构名称：" prop="authenticationName">
                        <el-input v-model="formData.authenticationName" placeholder="请输入机构名称" clearable
                            :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="11">
                    <el-form-item label="授权账号：" prop="authorizedAccountId">
                        <div style="display: flex;">
                            <el-select v-model="authorizedAccountId" disabled multiple placeholder="授权账号">
                                <el-option v-for="item in authMyList" :key="item.value" :label="item.accountName"
                                    :value="item.accountId">
                                </el-option>
                            </el-select>
                            <el-form-item label-width="20px">
                                <el-button type="primary" size="mini" @click="toAuth"> +新授权 </el-button>
                            </el-form-item>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="电子邮箱：">
                        <el-input v-model="formData.email" placeholder="请输入电子邮箱" clearable :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="联系方式：" prop="tel">
                        <el-input v-model="formData.tel" placeholder="请输入联系方式" clearable :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="机构简介：" prop="shortDescription">
                        <el-input v-model="formData.shortDescription" placeholder="请输入机构简介" clearable
                            :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="机构地址：" prop="postalAddress">
                        <el-input v-model="formData.postalAddress" placeholder="请输入机构地址" clearable
                            :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="14">
                    <el-form-item label="营业执照：" label-width="120px" prop="valiDoctor" required style="width:480px;">
                        <el-upload ref="media" class="upload-demo" :file-list="mediafileList" :limit="1"
                            :action="mediaAction" :auto-upload="true" :on-error="upFail"
                            :before-upload="uploadBeforeUpload" :on-success="uploadContent" :headers="headers"
                            :data="{ folderType: 7 }" :show-file-list="false"
                            :before-remove="() => { formData.valiDoctor = false; mediafileList = [] }">
                            <div class="box_add">
                                <div v-if="mediafileList.length > 0" style="height: 170px;">
                                    <img :src="mediafileList[0].url" width="330" height="165">
                                    <div style="color:#165DFF ;font-size: 18px;"
                                        @click.stop="() => { formData.valiDoctor = false; mediafileList = [] }">删除</div>
                                </div>
                                <div v-if="mediafileList.length < 1"><i class="el-icon-plus"
                                        style="font-size: 30px"></i></div>
                                <div class="el-upload__text" v-if="mediafileList.length < 1">支持扩展名:.png、jpeg、.jpg，最大10M
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="22">
                    <el-form-item label="科普目的：" prop="createPurposes" style="margin-top: 30px;">
                        <el-checkbox-group v-model="createPurpose" size="medium">
                            <el-checkbox v-for="(item, index) in checkListOptions" :key="index" :label="item.value"
                                :disabled="item.disabled">{{ item.label }}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item size="large" style="text-align: center;padding-left: 90px;">
                        <el-button type="primary" @click="submitForm">保存认证信息</el-button>
                    </el-form-item>
                </el-col>
            </el-form>
        </el-row>
    </div>
</template>

<script>
import { getScanCodeAuthUrl, authenticationDataUser, systemAuthLists, getInfoByUserId, UpdateDataUser, } from '@/api/my'
import { getToken } from "@/utils/auth";
export default {
    dicts: ['user_auth_doctor_rank', 'user_auth_role_type_two'],
    components: {},
    props: ['openHandle'],
    data() {
        return {
            validateFile: (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请选择一个文件'));
                } else {
                    callback();
                }
            },
            jobList: [   //职称类别
                {
                    "label": "医务从业者",
                    "value": "1"
                },
                {
                    "label": "其他",
                    "value": "2"
                }
            ],
            hospList: [   //职称类别
                {
                    "label": "郑州大学第一附属医院",
                    "value": "1"
                },
                {
                    "label": "洛阳骨科医院",
                    "value": "2"
                },
                {
                    "label": "郑州市人民医院",
                    "value": "3"
                },
            ],
            authMyList: [],
            createPurpose: [],              //科普目的
            authorizedAccountId: undefined,  //授权账号
            formData: {
                userName: '',  //用户手机号
                type: undefined,  //类别
                doctorRank: undefined,    //医生职称
                hospitalName: undefined,   //所属医院名称
                authenticationName: undefined,  // 姓 名
                authorizedAccountId: undefined,  //授权账号
                shortDescription: undefined,     //简 介
                email: undefined,                //电子邮箱
                tel: undefined,                 //联系方式
                postalAddress: undefined,       //邮政地址
                createPurposes: [],              //科普目的,为了表单验证
                createPurpose: [],              //科普目的
                proofUrl: '',                     //凭证资料url（多个资料，号分隔）
                roleType: 2,                  //认证类型创作者（1：个人认证资料 2：机构认证资料）3：新媒体4：审核者
                // media: '',        //没啥用就是验证用的
                valiDoctor: '',      //没啥用就是验证用的
            },
            headers: {
                Authorization: "Bearer " + getToken()
            },
            rules: {
                userName: [{
                    required: true,
                    message: '默认用户登录用户名',
                    trigger: 'blur'
                }, {
                    pattern: /^1(3|4|5|7|8|9)\d{9}$/,
                    message: '请填写正确手机号码',
                    trigger: 'blur'
                }],
                ///^([a-zA-Z0-9_.&*-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$/; 
                type: [{
                    required: true,
                    message: '请选择机构类型',
                    trigger: 'blur'
                }],
                authenticationName: [{
                    required: true,
                    message: '请输入机构名称',
                    trigger: 'blur'
                }],
                authorizedAccountId: [],
                shortDescription: [],
                email: [
                    {
                        required: true,
                        message: '电子邮件格式错误',
                        trigger: 'blur'
                    }, {
                        pattern: /^([a-zA-Z0-9_.&*-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$/,
                        message: '电子邮件格式错误',
                        trigger: 'blur'
                    }
                ],
                media: [
                    { required: true, validator: this.validateFile, trigger: 'change' },
                ],
                tel: [{
                    required: true,
                    message: '请填写联系方式',
                    trigger: 'blur'
                },
                    //  {
                    //     pattern: /^1(3|4|5|7|8|9)\d{9}$/,
                    //     message: '手机号格式错误',
                    //     trigger: 'blur'
                    // }
                ],
                postalAddress: [],
                createPurpose: [{
                    required: true,
                    type: 'array',
                    message: '请至少选择一个科普目的',
                    trigger: 'change'
                }],
                valiDoctor: [{
                    required: true,
                    message: '请选择上传营业执照证',
                    trigger: 'change'
                }],
            },
            mediafileList: [],
            imgHeader: process.env.VUE_APP_ImgUrlHeader,
            mediaAction: process.env.VUE_APP_BASE_API + "/common/resourceFileUpload",
            // uploadAction: process.env.VUE_APP_BASE_API + "/common/commonFileUpload",
            uploadfileList: [],
            docListOptions: [{
                "label": "医务从业人员",
                "value": "isDoctor"
            }],
            checkListOptions: [{
                "label": "课题管理",
                "value": 1
            }, {
                "label": "公益科普",
                "value": 2
            }, {
                "label": "文化传播",
                "value": 3
            }, {
                "label": "创作协同",
                "value": 4
            }, {
                "label": "健康科普",
                "value": 5
            }, {
                "label": "中医问诊",
                "value": 6
            }],
        }
    },
    computed: {
        imgEndUrl(url) {
            // return 123
            return (url) => {
                //  console.log(url,123);
                // const url = "https://ossapi.169000.net/zyykp/sourceMaterialImg/2024/01/22/hushi_20240122152939A001.jpeg";
                const filenameRegex = /.*\/([^/]*?)$/;
                const match = url.match(filenameRegex);
                if (match) {
                    return match[1]
                    console.log(match[1]);  // 输出: hushi_20240122152939A001.jpeg  
                } else {
                    console.log("没有找到文件名");
                    return url
                }
            }
        }
    },
    watch: {
        openHandle(ne, ol) {
            if (!ne) {
                this.removeDoc()
            }
            this.init()
            //console.log(ne,123);
        }
    },
    async created() {
        await this.AuthList()
        this.init()
    },
    mounted() { },
    methods: {
        removeDoc() {
            this.mediafileList = []
            this.formData.valiDoctor = []
            this.$refs['elForm'].resetFields()
        },
        init() {
            this.getAuthMyList()
            // console.log();

        },
        async getAuthMyList() {
            // if (this.$store.state.user.roles[0] == 'ordinaryUser') {
            //     this.formData.userName = this.$store.state.user.phone  //用户手机号
            //     return
            // }
            let res = await getInfoByUserId(this.$store.state.user.userId)
            //  let r = res.data.map(v =>{
            //       v.createPurpose = Number(v.createPurpose)
            //       return v
            //     })
            if (this.authMyList.length > 0) {
                this.authorizedAccountId = this.authMyList.reduce((pre, value, index) => {
                    pre.push(value.accountId)
                    return pre
                }, [])
            }
            if (res.code == 200 && !this.isEmptyObject(res.data) && res.data.roleType == 2) {
                try {
                    this.formData.email = res.data.email
                    this.formData.postalAddress = res.data.postalAddress
                    this.formData.proofUrl = res.data.proofUrl
                    this.mediafileList = [{ url: this.imgHeader + res.data.proofUrl, name: this.imgEndUrl(res.data.proofUrl) }]
                    this.formData.roleType = res.data.roleType
                    this.formData.shortDescription = res.data.shortDescription
                    this.formData.tel = res.data.tel
                    if (res.data.type) this.formData.type = res.data.type.toString()
                    this.formData['userDataId'] = res.data.userDataId
                    this.formData.userId = res.data.userId
                    this.formData.userName = res.data.userName
                    this.formData.authenticationName = res.data.authenticationName
                    if (res.data.createPurpose.length > 0) this.createPurpose = res.data.createPurpose.split(',')
                    if (this.createPurpose.length > 0) this.createPurpose = this.createPurpose.map(v => Number(v))
                    if (this.authMyList.length > 0) {
                        this.authorizedAccountId = this.authMyList.reduce((pre, value, index) => {
                            pre.push(value.accountId)
                            return pre
                        }, [])
                    }
                } catch (e) {
                    console.log(e);
                }
                // this.formData.authorizedAccountId =  res.data.authorizedAccountList.map(v=>{
                // })
            } else {
                if (res.data.userDataId) {
                    this.formData['userDataId'] = res.data.userDataId
                }
                this.formData.userName = this.$store.state.user.phone  //用户手机号
                //  this.formData.authenticationName = this.$store.state.user.nickName  // 姓 名
            }
            //  console.log(res);
        },
        isEmptyObject(obj) {
            return JSON.stringify(obj) === '{}';
        },
        async AuthList() {  //授权列表
            let res = await systemAuthLists({ userId: this.$store.state.user.userId })
            if (res.code == 200) {
                this.authMyList = res.rows
            }
            //console.log(res,'----');
        },
        async toAuth() {  //新授权
            let res = await getScanCodeAuthUrl(this.$store.state.user.userId)
            //let res = await getScanCodeAuthUrl()
            window.location.href = res.data;
            // console.log(res);
            // alert(123)
        },
        async save() {
            this.formData.createPurpose = this.createPurpose.join()
            if (this.formData.userDataId !== undefined) {
                let result = await UpdateDataUser(this.formData)
                if (result.code == 200) {
                    this.$message.success({
                        title: '提示',
                        message: '更新认证成功'
                    })
                    this.mediafileList = []
                    this.formData.valiDoctor = []
                    this.$emit('closeDia', { name: 'chuangzuozhe', isClose: false })
                }
                return
            }
            // console.log(this.formData,'ppp');
            if (this.mediafileList > 0) {
                this.$refs.forms.clearValidate("media");  //当图片数量大于0则去除校验提示
            }
            let res = await authenticationDataUser(this.formData)
            if (res.code == 200) {
                this.$emit('closeDia', { name: 'chuangzuozhe', isClose: false })
                this.$message.success({ title: '提示', message: res.msg })
                // this.$store.dispatch('LogOut').then(() => {
                //     location.href = '/index';
                // })
            }
        },
        upFail(err, file, fileList) {
            //上传失败
            // console.log(err,'llll');
            this.$message.error('上传失败，请稍后再重试')
        },
        submitForm() {
            if (this.$refs['media'].uploadFiles.length < 1) {
                this.formData.valiDoctor = null
            } else {
                this.formData.valiDoctor = true  //如果上传就赋值，下面会通过验证，然后再清空赋值
            }
            this.$refs['elForm'].validate(valid => {
                if (this.formData.valiDoctor == null) return
                if (!valid) return
                this.save()
                // TODO 提交表单
            })
        },
        resetForm() {
            this.$refs['elForm'].resetFields()
        },
        uploadBeforeUpload(file) {
            let isRightSize = file.size / 1024 / 1024 < 100
            if (!isRightSize) {
                this.$message.error('文件大小超过 100MB')
                return false
            }
            const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
            if (!isImage) {
                this.$message.error('应该选择png，jpg，jpeg类型的文件');
                return false;
            }
            return isRightSize && isImage
        },
        submitUpload() {
            this.$refs['upload'].submit()
        },
        uploadContent(response, file, fileList) {  //内容封面
            if (response.code == 200) {
                this.formData.proofUrl = response.data.filePath
                // console.log(this.formData.proofUrl, 'sssss');
                // this.form.coverUrl = response.data.filePath
                this.mediafileList.push({ url: response.data.url + response.data.filePath, name: this.imgEndUrl(response.data.filePath) })
                this.$message.success({
                    title: '提示',
                    message: '上传营业执照成功'
                })
            } else {
                this.formData.valiDoctor = []
                this.$message.info('上传图片失败，请稍后重试')
            }
            //  console.log(response, 123);
        },
        mediaBeforeUpload(file, fileList) {
            const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
            if (!isImage) {
                this.$message.error('应该选择png，jpg，jpeg类型的文件');
                return false;
            }
            let isRightSize = file.size / 1024 / 1024 < 10
            if (!isRightSize) {
                this.$message.error('文件大小超过 10MB')
                return false
            }
            return isRightSize && isImage
        },
    }
}

</script>

<style>
.el-upload__tip {
    line-height: 1.2;
}
</style>

<style lang="scss" scoped>
::v-deep .el-select {
    width: 410px;
}

::v-deep .el-upload-dragger {
    width: 330px !important;
}

.box_add {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    width: 330px;
    height: 150px;
    border: 1px dashed #ccc;
    border-radius: 8px;
    margin-top: 10px;
}
</style>